package middlewares

import (
	"fmt"
	"logging"
	"net/http"

	"api/go-demo/utils"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

const (
	secretKey = "88mkva4N{3m47/sm"
)

// GetJWTToken 获取JWTToken
func GetJWTToken(ctx *gin.Context) *utils.Claims {
	c, exist := ctx.Get("token")
	if exist {
		return c.(*utils.Claims)
	}
	return nil
}

// Auth 验证 token
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// logging.Debugf("header: %v\n", c.Request.Header)
		jwtToken := c.Request.Header.Get("x-fxb-jwt")

		// fmt.Printf("jwt:%v", jwtToken)
		token, err := jwt.ParseWithClaims(jwtToken, &utils.Claims{}, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("Unexpected signing method")
			}
			return []byte(secretKey), nil
		})
		if err != nil {
			logging.Errorf("jwtAuth: err:%v\n", err)

			c.JSON(http.StatusUnauthorized, gin.H{"errno": "-1", "errmsg": "unauthorized"})
			c.Abort()
			return
		}

		// 判断token是否有效
		claims, ok := token.Claims.(*utils.Claims)
		if !ok || !token.Valid {
			logging.Errorf("jwtAuth: err:%v\n", err)

			c.JSON(http.StatusUnauthorized, gin.H{"errno": "-1", "errmsg": "unauthorized"})
			c.Abort()
			return
		}

		c.Set("token", claims)

		c.Next()
	}
}
